package com.wanxi.newstype.controller;



import com.wanxi.common.result.ImgDTO;
import com.wanxi.common.result.ResultDTO;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;

@Controller
public class UploadController {

    // 上传文件存储目录
    private static final String UPLOAD_DIRECTORY = "upload";

    @RequestMapping(value = "/upload")
    @ResponseBody
    public ResultDTO upload(MultipartFile file, HttpServletRequest req) {


        if (file == null) {
            ResultDTO resultDTO = ResultDTO.builder()
                    .code(0)
                    .msg("Error: null of upload file")
                    .build();
            return resultDTO;
        }

        String fileName = file.getOriginalFilename();
//                        需要将当前的文件名修改，唯一的文件名（同一个文件夹里面不能有相同的文件名）
//                       d:/aa/b/upload/ 16543456787654--a.jpg
        fileName = System.currentTimeMillis() + "--" + fileName;


        // 构造临时路径来存储上传的文件
        // 这个路径相对当前应用的目录
        String uploadPath = req.getServletContext().getRealPath("./") + File.separator + UPLOAD_DIRECTORY;
        // 如果目录不存在则创建
        createDir(uploadPath);

        String filePath = uploadPath + File.separator + fileName;
        File storeFile = new File(filePath);


        try {

            file.transferTo(storeFile);

            {
//                            得到web目录下面的upload地址
                String path = "E:\\chenming\\step-eight\\springcloud-web\\out\\artifacts\\springcloud_web_war_exploded\\upload";
//                            创建文件夹
                createDir(path);
//                            得到web目录下文件的路径
                File webFile = new File(path, fileName);
//                            将item写道新地址
//                            item可以理解为只能用一次
//                            item.write(webFile);
                copy(storeFile, webFile);
            }

            //                        返回给前端的路径
            String path = "/" + UPLOAD_DIRECTORY + "/" + fileName;
            ImgDTO imgDTO = new ImgDTO(path);
            ResultDTO resultDTO = ResultDTO.builder()
                    .code(0)
                    .msg("")
                    .data(imgDTO)
                    .build();
            return resultDTO;

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;

    }


    private void copy(File storeFile, File webFile) {
        try (InputStream inputStream = new FileInputStream(storeFile);
             OutputStream outputStream = new FileOutputStream(webFile)) {
            int read = 0;
            while ((read = inputStream.read()) != -1) {
                outputStream.write(read);
            }
        } catch (Exception e) {

        }
    }

    /**
     * 创建文件夹
     *
     * @param uploadPath
     */
    private void createDir(String uploadPath) {
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }
    }

}
